<template>
  <div class="new-post-section">
    <div class="post-header">
      <div class="header-tab active">动态</div>
      <a href="/write/article" target="_blank" class="header-tab">文章</a>
    </div>

    <div class="post-content-area">
      <input
          type="text"
          v-model="title"
          placeholder="好的标题会获得更多曝光~"
          class="post-title-input"
      />
      <div class="word-count">{{ title.length }}/50</div>

      <div
          ref="contentEditableDiv"
          contenteditable="true"
          class="post-content-editable"
          @input="updateContent"
          @focus="isContentEditableFocused = true"
          @blur="isContentEditableFocused = false"
      >
      </div>

      <span
          v-if="!hasContent && !isContentEditableFocused"
          class="placeholder-text"
      >
    随便说说，问你想问
  </span>

      <div class="content-word-count">{{ pureContentLength }}/5000</div>
    </div>

    <div class="post-actions-row">
      <div class="action-buttons-left">
        <button class="action-btn icon-btn"><span class="icon">+</span></button>
        <button class="action-btn" @click="showAddTopicModal = true">添加标签</button>
        <button
            v-for="tag in filterTags"
            :key="tag.type"
            class="action-btn"
            :class="{ 'active-filter': selectedFilter === tag.type }"
            @click="selectFilter(tag.type)"
        >
          {{ tag.name }}
        </button>
      </div>
      <div class="action-buttons-right">
        <button @click="handleSubmit" :disabled="!isFormValid" class="action-btn submit-btn">
          发布
        </button>
      </div>
    </div>

    <div class="tags-section">
      <span class="tag-label">标签:</span>
      <div class="tag-list">
        <span
            class="tag-item"
            v-for="tag in defaultTags"
            :key="tag"
            @click="addTopicToContent(tag)"
        >
          #{{ tag }}#
        </span>
        <span
            class="tag-item custom-tag-item"
            v-for="tag in customTags"
            :key="tag"
            @click="addTopicToContent(tag)"
        >
          #{{ tag }}#
          <span class="remove-tag-btn" @click.stop="removeCustomTag(tag)">x</span>
        </span>
      </div>
    </div>

    <div v-if="showAddTopicModal" class="modal-overlay">
      <div class="modal-content">
        <h3>添加自定义话题</h3>
        <input
            type="text"
            v-model="newTopicInput"
            placeholder="请输入话题内容，无需带 # 号"
            class="modal-input"
            @keyup.enter="addCustomTopic"
        />
        <div class="modal-actions">
          <button @click="showAddTopicModal = false" class="modal-btn cancel-btn">取消</button>
          <button @click="addCustomTopic" :disabled="!newTopicInput.trim()" class="modal-btn confirm-btn">
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, computed, defineEmits, nextTick, onMounted } from 'vue';
import { postService } from "@/services/PostService.js";
import {userManager} from "@/utils/user.js"
import {ElMessage} from 'element-plus'
import creditService from '@/services/creditService';
import { methods } from '@/utils/methods';

const emits = defineEmits(['submitPost']);

const contentEditableDiv = ref(null);
const title = ref('');
const content = ref('');
const isContentEditableFocused = ref(false);
const showAddTopicModal = ref(false);
const newTopicInput = ref('');
const customTags = ref([]);
const todayPostArticleNum=ref(0)//今天已发送的帖子文章数

const defaultTags = ref([
  '考研VS就业，你怎么选？',
  '24届的你们现状如何了？',
  '创客创作奖金赛',
]);

onMounted(()=>{
    postService.getTodayPostArticleNum(userManager.getUserId(),(res)=>{
      todayPostArticleNum.value=res.data
  })
})



const selectedFilter = ref('recommend');

const filterTags = ref([
  { name: '圈子', type: 'circle' },
  { name: '薪资爆料', type: 'salary' },
  { name: '选offer', type: 'offer' },
  { name: '面经', type: 'interview' },
  { name: '聊公司', type: 'company' },
]);

const selectFilter = (filterType) => {
  selectedFilter.value = filterType;
};

const hasContent = computed(() => {
  if (!content.value) return false;
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = content.value;
  return tempDiv.innerText.trim().length > 0;
});
const pureContentLength = computed(() => {
  if (!content.value) return 0;
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = content.value;
  return tempDiv.innerText.trim().length;
});
const isFormValid = computed(() => title.value.trim() !== '' || hasContent.value);

const updateContent = (event) => {
  content.value = event.target.innerHTML;
};

const addTopicToContent = (topic) => {
  const editableDiv = contentEditableDiv.value;
  if (!editableDiv) return;

  const formattedTopicHtml = `<span class="inserted-topic">#${topic}#</span><br>`;

  if (!editableDiv.innerHTML.includes(`#${topic}#`)) {
    editableDiv.innerHTML = formattedTopicHtml + editableDiv.innerHTML;
    content.value = editableDiv.innerHTML;

    nextTick(() => {
      editableDiv.focus();
      const range = document.createRange();
      const sel = window.getSelection();
      range.selectNodeContents(editableDiv);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
    });
  }
};

const addCustomTopic = () => {
  const topic = newTopicInput.value.trim();
  if (topic && !customTags.value.includes(topic)) {
    customTags.value.push(topic);
    newTopicInput.value = '';
    showAddTopicModal.value = false;
  } else if (topic && customTags.value.includes(topic)) {
    alert('该话题已存在，请勿重复添加！');
  }
};

const removeCustomTag = (tagToRemove) => {
  customTags.value = customTags.value.filter(tag => tag !== tagToRemove);
  const editableDiv = contentEditableDiv.value;
  if (editableDiv) {
    const regex = new RegExp(`<span[^>]*>#${tagToRemove}#</span><br>?`, 'g');
    editableDiv.innerHTML = editableDiv.innerHTML.replace(regex, '');
    content.value = editableDiv.innerHTML;
  }
};

const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.error('标题或内容不能为空！');
    return;
  }
  const postData = {
    author:userManager.getUserId(),
    title: title.value,
    content: content.value,
    filtertype: selectedFilter.value
  };
  try {
    const response = await postService.createPost(postData);
    ElMessage.success('发布成功！');
    todayPostArticleNum.value++

    if(todayPostArticleNum.value<=5){

      creditService.addNewCredit(5,null,methods.FORUM_ACTIVITY,userManager.getUserId(),(res)=>{

      })
      ElMessage.success('学分增加5分还剩'+(5-todayPostArticleNum.value)+'次加学分的机会');

      
    }
    
    title.value = '';
    content.value = '';
    customTags.value = [];
    if (contentEditableDiv.value) {
      contentEditableDiv.value.innerHTML = '';
    }

    emits('submitPost', postData);

  } catch (error) {
    console.error('组件中捕获到错误:', error);
    ElMessage.error(error.message || '发布失败，请检查网络或联系管理员。');
  }
};
</script>



<style scoped>

.header-tab {
  text-decoration: none;
  padding: 12px 20px;
  font-size: 15px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: border-bottom-color 0.2s, color 0.2s;
}
.action-btn.active-filter {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.action-btn.active-filter:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.new-post-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  overflow: hidden;
  position: relative; /* 确保弹窗定位在其上方 */
}

.post-header {
  display: flex;
  border-bottom: 1px solid #eee;
}

.post-header .header-tab {
  padding: 12px 20px;
  font-size: 15px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: border-bottom-color 0.2s, color 0.2s;
}

.post-header .header-tab.active {
  color: #409eff;
  font-weight: bold;
  border-bottom-color: #409eff;
}

.post-content-area {
  padding: 15px 20px 0;
  position: relative;
}

.post-title-input {
  width: calc(100% - 20px);
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 16px;
  margin-bottom: 10px;
  box-sizing: border-box;
}
.post-title-input::placeholder {
  color: #bbb;
}

.post-content-editable {
  width: calc(100% - 20px);
  min-height: 80px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  box-sizing: border-box;
  overflow-y: auto;
  word-wrap: break-word;
  white-space: pre-wrap;
  cursor: text;
}

.post-content-editable:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
  outline: none;
}

.placeholder-text {
  color: #bbb;
  font-size: 14px;
  position: absolute;
  top: 75px;
  left: 32px;
  pointer-events: none;
}

.inserted-topic {
  background-color: #e6ffe6;
  color: #228b22;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  margin-right: 5px;
  font-weight: bold;
  white-space: nowrap;
}


.word-count {
  position: absolute;
  top: 30px;
  right: 30px;
  font-size: 12px;
  color: #999;
}

.content-word-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  padding-right: 10px;
}


.post-actions-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-top: 1px solid #eee;
  flex-wrap: wrap;
}

.action-buttons-left, .action-buttons-right {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  background-color: #f8f8f8;
  color: #666;
  border: 1px solid #e0e0e0;
  transition: background-color 0.2s, border-color 0.2s;
}

.action-btn:hover:not(:disabled) {
  background-color: #f0f0f0;
  border-color: #d0d0d0;
}

.action-btn.icon-btn {
  padding: 6px 10px;
  font-size: 18px;
}

.action-btn.disabled-btn {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
  border-color: #eee;
}

.submit-btn {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.submit-btn:hover:not(:disabled) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.submit-btn:disabled {
  background-color: #a0cfff;
  border-color: #a0cfff;
  cursor: not-allowed;
}

.tags-section {
  padding: 10px 20px 15px;
  border-top: 1px dashed #eee;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.tag-label {
  font-size: 13px;
  color: #999;
  margin-right: 10px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  background-color: #e6f7ff;
  color: #1890ff;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  white-space: nowrap;
  cursor: pointer;
  transition: background-color 0.2s;
}

.tag-item:hover {
  background-color: #d1efff;
}

/* 新增：自定义话题样式 */
.custom-tag-item {
  position: relative;
  background-color: #dbeaff; /* 浅蓝色背景区分自定义 */
  color: #0056b3; /* 深蓝色文字 */
  padding-right: 20px; /* 为关闭按钮留出空间 */
}

.remove-tag-btn {
  position: absolute;
  top: -6px; /* 向上微调 */
  right: 2px;
  font-size: 10px;
  font-weight: bold;
  color: #888;
  cursor: pointer;
  background-color: #fff;
  border-radius: 50%;
  width: 14px;
  height: 14px;
  line-height: 14px;
  text-align: center;
  border: 1px solid #ccc;
  transition: color 0.2s, background-color 0.2s;
}

.remove-tag-btn:hover {
  color: #f00;
  background-color: #eee;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保在最上层 */
}

.modal-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  width: 400px;
  max-width: 90%;
  text-align: center;
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 25px;
  color: #333;
  font-size: 20px;
}

.modal-input {
  width: calc(100% - 20px);
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  margin-bottom: 25px;
}

.modal-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.modal-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s, border-color 0.2s;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-btn {
  background-color: #409eff;
  color: white;
  border: 1px solid #409eff;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.confirm-btn:disabled {
  background-color: #a0cfff;
  border-color: #a0cfff;
  cursor: not-allowed;
}
</style>